package com.easypay.reactive8583.netty.pipeline;

import com.easypay.reactive8583.client.Iso8583Client;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author pandans
 * @date 2021/03/04 17:52
 * @Description:
 */
public class ReconnectOnCloseListener implements ChannelFutureListener {
    private Iso8583Client client;
    private int reconnectInterval;
    private ScheduledExecutorService executorService;

    public ReconnectOnCloseListener(Iso8583Client client, int reconnectInterval, ScheduledExecutorService executorService) {
        this.client = client;
        this.reconnectInterval = reconnectInterval;
        this.executorService = executorService;
    }

    private Logger logger = LoggerFactory.getLogger(ReconnectOnCloseListener.class);
    private AtomicBoolean disconnectRequested = new AtomicBoolean(false);

    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
    }

    public void requestReconnect() {
        disconnectRequested.set(false);
    }

    public void requestDisconnect() {
        disconnectRequested.set(true);
    }

    public void scheduleReconnect() {
        if (!disconnectRequested.get()) {
            logger.trace("Failed to connect. Will try again in {} millis", reconnectInterval);
            executorService.schedule((Callable<? extends Object>) client.connectAsync(), (long) reconnectInterval, TimeUnit.MILLISECONDS);
        }
    }


}
